package com.hp.authweb.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hp.authweb.bean.Result;
import com.hp.authweb.model.MenuInfo;
import com.hp.authweb.repository.MenuRepository;

/**
 * @Description:菜单管理
 * @author hp
 * @date 2018年5月20日 上午9:15:59
 */
@Service
public class MenuService {

	@Autowired
	private MenuRepository menuRep;
	
	/***
	 * 获取所有的菜单tree
	 * @return
	 */
	public List<MenuInfo> allTreeMenu(){
		return treeMenu(menuRep.findAll());
	}
	
	
	public List<MenuInfo> treeMenu(List<MenuInfo> menuList){
		
		// 子菜单
	    List<MenuInfo> treeList = new ArrayList<MenuInfo>();
	    menuList.forEach(action->{
	    	if(StringUtils.isEmpty(action.getParentsId())){
	    		treeList.add(findChildren(action,menuList));
	    	}
	    });
	    return treeList;
	}
	
	private MenuInfo findChildren(MenuInfo menu, List<MenuInfo> menuList){
		menuList.forEach(action->{
			if(String.valueOf(menu.getId()).equals(action.getParentsId())){
				if(menu.getChildList()==null){
					menu.setChildList(new ArrayList<MenuInfo>());
				}
				menu.getChildList().add(findChildren(action, menuList));
				
			}
		});
		
		return menu;
	}


	public Result saveMenu(MenuInfo menu) {
		try {
			menuRep.save(menu);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
		return Result.success();
	}
} 
